package com.test.nnooolwdeaer.activity_fragment_wooden.login_wooden;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.TextView;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.IntentSenderRequest;
import androidx.activity.result.contract.ActivityResultContracts;

import com.google.android.gms.auth.api.identity.GetPhoneNumberHintIntentRequest;
import com.google.android.gms.auth.api.identity.Identity;
import com.test.nnooolwdeaer.R;
import com.test.nnooolwdeaer.activity_fragment_wooden.base_wooden.BaseApplication_wooden;
import com.test.nnooolwdeaer.activity_fragment_wooden.base_wooden.BaseLoginActivity_wooden;
import com.test.nnooolwdeaer.bean_wooden.StaticVariate_wooden;
import com.test.nnooolwdeaer.bean_wooden.config_info_wooden.AppShowInfo_wooden;
import com.test.nnooolwdeaer.bean_wooden.config_info_wooden.GlobalConfig_wooden;
import com.test.nnooolwdeaer.bean_wooden.user_info_wooden.LoginInfo_wooden;
import com.test.nnooolwdeaer.constant_wooden.Constant_wooden;
import com.test.nnooolwdeaer.dialog_wooden.AppUpdateDialog_wooden;
import com.test.nnooolwdeaer.dialog_wooden.UpgradeDialog_wooden;
import com.test.nnooolwdeaer.util_wooden.StringUtil_wooden;
import com.test.nnooolwdeaer.util_wooden.analytics_wooden.timezone_wooden.TimeZoneHostEnum_wooden;
import com.test.nnooolwdeaer.util_wooden.helper_wooden.UserInfoHelper_wooden;
import com.test.nnooolwdeaer.util_wooden.http_wooden.HttpManager_wooden;
import com.test.nnooolwdeaer.view_wooden.TrackEditText;
import com.test.nnooolwdeaer.view_wooden.widget_wooden.SelectView_wooden;
import com.test.nnooolwdeaer.util_wooden.analytics_wooden.util_wooden.AnalyticsUtil_wooden;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.TimeZone;

public class LoginPhoneNumActivity_wooden extends BaseLoginActivity_wooden {

    private SelectView_wooden countrySv_wooden;
    private TextView prefixTv_wooden;
    private TrackEditText phoneNumEt_wooden;

    private TextView mobileTitleTv_wooden;


    private boolean phoneNumberHintFlag = true;

    private final ActivityResultLauncher<IntentSenderRequest> phoneNumberHintLauncher = registerForActivityResult(
            new ActivityResultContracts.StartIntentSenderForResult(),
            result -> {
                try {

                    String mobile = Identity.getSignInClient(this).getPhoneNumberFromIntent(result.getData());

                    if (TextUtils.isEmpty(mobile)) return;

                    String mobilePrefix = StaticVariate_wooden.getMobilePrefix_wooden();

                    phoneNumEt_wooden.setText(mobile.startsWith(mobilePrefix) ? mobile.replace(mobilePrefix,"").trim():mobile);

                } catch (Exception e) {
                    if (Constant_wooden.Debug) e.printStackTrace();
                }
            }
    );


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_phone_num_wooden);
        init_wooden();
    }

    @SuppressLint("SetTextI18n")
    private void init_wooden() {

        countrySv_wooden = findViewById(R.id.activity_login_phone_num_sv_country);
        prefixTv_wooden = findViewById(R.id.activity_login_phone_num_tv_prefix);
        phoneNumEt_wooden = findViewById(R.id.activity_login_phone_num_et_phone_num);
        mobileTitleTv_wooden = findViewById(R.id.activity_login_phone_num_tv_mobile_title);

        phoneNumEt_wooden.sTrackWord(getClass().getSimpleName().toUpperCase()+"_PHONE_NUMBER_INPUT");

        phoneNumEt_wooden.addTextChangedListener(new TextWatcher() {
            @Override
            public void afterTextChanged(Editable editable) {}

            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.length()>=8){
                    String phoneNum = charSequence.toString();
                    String accountToken = GlobalConfig_wooden.getInstance_wooden().isTestAccount_wooden(phoneNum);
                    if (!TextUtils.isEmpty(accountToken)) {
                        try {
                            JSONObject object = new JSONObject();
                            object.put("token", accountToken);
                            object.put("userId", phoneNum);
                            object.put("typ", UserInfoHelper_wooden.LOGIN_TYPE_OLD_wooden);
                            LoginInfo_wooden.parse_wooden(object);
                            onUserLoginResponse_wooden();
                        } catch (Exception e) {
                            if (Constant_wooden.Debug) e.printStackTrace();
                        }
                    }
                }
            }
        });

        ArrayList<String> countries = GlobalConfig_wooden.getInstance_wooden().getCountries_wooden();
        ArrayList<String> countriesName = new ArrayList<>();

        findViewById(R.id.activity_login_phone_num_btn_next).setOnClickListener(v -> {

            HttpManager_wooden.getInstance_wooden().saveUserBuriedPointAndUpload(getClass().getSimpleName().toUpperCase()+"_NEXT_CLICK");

            if (TextUtils.isEmpty(countrySv_wooden.getInput_wooden()) || TextUtils.isEmpty(phoneNumEt_wooden.gText())) {
                showToast_wooden(getString(R.string.word_input_tip));
                return;
            }

            String phoneNum = StringUtil_wooden.getSafeString_wooden(phoneNumEt_wooden.gText());

            //测试账号登录
            String accountToken = GlobalConfig_wooden.getInstance_wooden().isTestAccount_wooden(phoneNum);
            if (!TextUtils.isEmpty(accountToken)) {
                try {
                    JSONObject object = new JSONObject();
                    object.put("token", accountToken);
                    object.put("userId", phoneNum);
                    object.put("typ", UserInfoHelper_wooden.LOGIN_TYPE_OLD_wooden);
                    LoginInfo_wooden.parse_wooden(object);
                    onUserLoginResponse_wooden();
                } catch (Exception e) {
                    if (Constant_wooden.Debug) e.printStackTrace();
                }
                return;
            }

            HttpManager_wooden.getInstance_wooden().requestOtpCode_wooden(phoneNum);
        });

        //国家选择初始化
        String timeZoneId = TimeZone.getDefault().getID();
        if (timeZoneId.equalsIgnoreCase(TimeZoneHostEnum_wooden.TimeZoneFcfa.getTimeZoneId()) && countries.contains(Constant_wooden.WordPrefix_wooden + Constant_wooden.Suffix_Cote_wooden)) {
            selectCountry_wooden(Constant_wooden.Country_Cote_wooden);
            countrySv_wooden.setInput_wooden(Constant_wooden.Country_Cote_wooden);
            countrySv_wooden.setVisibility(View.GONE);
        } else if (timeZoneId.equalsIgnoreCase(TimeZoneHostEnum_wooden.TimeZoneGha.getTimeZoneId()) && countries.contains(Constant_wooden.WordPrefix_wooden + Constant_wooden.Suffix_Ghana_wooden)) {
            selectCountry_wooden(Constant_wooden.Country_Ghana_wooden);
            countrySv_wooden.setInput_wooden(Constant_wooden.Country_Ghana_wooden);
            countrySv_wooden.setVisibility(View.GONE);
        } else if (timeZoneId.equalsIgnoreCase(TimeZoneHostEnum_wooden.TimeZoneKsh.getTimeZoneId()) && countries.contains(Constant_wooden.WordPrefix_wooden + Constant_wooden.Suffix_Kenya_wooden)) {
            selectCountry_wooden(Constant_wooden.Country_Kenya_wooden);
            countrySv_wooden.setInput_wooden(Constant_wooden.Country_Kenya_wooden);
            countrySv_wooden.setVisibility(View.GONE);
        } else if (timeZoneId.equalsIgnoreCase(TimeZoneHostEnum_wooden.TimeZoneNaira.getTimeZoneId()) && countries.contains(Constant_wooden.WordPrefix_wooden + Constant_wooden.Suffix_Nigeria_wooden)) {
            selectCountry_wooden(Constant_wooden.Country_Nigeria_wooden);
            countrySv_wooden.setInput_wooden(Constant_wooden.Country_Nigeria_wooden);
            countrySv_wooden.setVisibility(View.GONE);
        } else if (timeZoneId.equalsIgnoreCase(TimeZoneHostEnum_wooden.TimeZoneUgx.getTimeZoneId()) && countries.contains(Constant_wooden.WordPrefix_wooden + Constant_wooden.Suffix_Uganda_wooden)) {
            selectCountry_wooden(Constant_wooden.Country_Uganda_wooden);
            countrySv_wooden.setInput_wooden(Constant_wooden.Country_Uganda_wooden);
            countrySv_wooden.setVisibility(View.GONE);
        } else if (timeZoneId.equalsIgnoreCase(TimeZoneHostEnum_wooden.TimeZoneVietnam.getTimeZoneId()) && countries.contains(Constant_wooden.WordPrefix_wooden + Constant_wooden.Suffix_Vietnam_wooden)) {
            selectCountry_wooden(Constant_wooden.Country_Vietnam_wooden);
            countrySv_wooden.setInput_wooden(Constant_wooden.Country_Vietnam_wooden);
            countrySv_wooden.setVisibility(View.GONE);
        } else {
            for (String country : countries) {
                if (country.endsWith(Constant_wooden.Suffix_Ghana_wooden)) {//加纳
                    countriesName.add(Constant_wooden.Country_Ghana_wooden);
                } else if (country.endsWith(Constant_wooden.Suffix_Uganda_wooden)) {//乌干达
                    countriesName.add(Constant_wooden.Country_Uganda_wooden);
                } else if (country.endsWith(Constant_wooden.Suffix_Cote_wooden)) {//科特
                    countriesName.add(Constant_wooden.Country_Cote_wooden);
                } else if (country.endsWith(Constant_wooden.Suffix_Kenya_wooden)) {//肯尼亚
                    countriesName.add(Constant_wooden.Country_Kenya_wooden);
                } else if (country.endsWith(Constant_wooden.Suffix_Nigeria_wooden)) {//尼日
                    countriesName.add(Constant_wooden.Country_Nigeria_wooden);
                } else if (country.endsWith(Constant_wooden.Suffix_Vietnam_wooden)) {//越南
                    countriesName.add(Constant_wooden.Country_Vietnam_wooden);
                }
            }
        }

        countrySv_wooden.addListItem_wooden(countriesName);
        countrySv_wooden.setInterceptPickListener(pickStr -> {
            selectCountry_wooden(pickStr);
            HttpManager_wooden.getInstance_wooden().getAppShowInfo_wooden();
        });


        if (countriesName.size()==1){
            String countryName = countriesName.get(0);
            countrySv_wooden.setInput_wooden(countryName);
            selectCountry_wooden(countryName);
            HttpManager_wooden.getInstance_wooden().getAppShowInfo_wooden();
        }

        //检查是否已登录
        if (UserInfoHelper_wooden.getInstance_wooden().didLogin_wooden()) {

            countrySv_wooden.setInput_wooden(UserInfoHelper_wooden.getInstance_wooden().getCountryName_wooden());
            prefixTv_wooden.setText(StaticVariate_wooden.getMobilePrefix_wooden());
            phoneNumEt_wooden.setText(UserInfoHelper_wooden.getInstance_wooden().getMobile_wooden());

            selectCountry_wooden(UserInfoHelper_wooden.getInstance_wooden().getCountryName_wooden());

        }

    }

    private void selectCountry_wooden(String countryName){

        StaticVariate_wooden.Select_Country_wooden = countryName;
        StaticVariate_wooden.Country_Word_wooden = Constant_wooden.WordPrefix_wooden + StringUtil_wooden.getSafeString_wooden(StaticVariate_wooden.Country_Suffix_Map_wooden.get(countryName));

        //登录前初始化
        AnalyticsUtil_wooden.INSTANCE.initDevice(BaseApplication_wooden.getApplication());
        AnalyticsUtil_wooden.INSTANCE.saveFirebaseS2SInfo();

        StaticVariate_wooden.Country_Config_wooden = GlobalConfig_wooden.getInstance_wooden().getCountryConfigTreeMap_wooden().get(StaticVariate_wooden.Country_Word_wooden);
        UserInfoHelper_wooden.getInstance_wooden().setCountryWord_wooden(StaticVariate_wooden.Country_Word_wooden);
        UserInfoHelper_wooden.getInstance_wooden().setCountryName_wooden(StaticVariate_wooden.Select_Country_wooden);
        String mobile = StaticVariate_wooden.Country_Config_wooden == null ? "" : StaticVariate_wooden.Country_Config_wooden.getCustomer();
        phoneNumEt_wooden.setHint(TextUtils.isEmpty(mobile) ? Constant_wooden.CUSTOMER_PHONE_wooden : mobile);

        String mobilePrefix = StaticVariate_wooden.getMobilePrefix_wooden();
        prefixTv_wooden.setText(mobilePrefix);

        phoneNumEt_wooden.setOnFocusChangeListener((v, hasFocus) -> {

            if (hasFocus && phoneNumberHintFlag){

                phoneNumberHintFlag = false;

                GetPhoneNumberHintIntentRequest request = GetPhoneNumberHintIntentRequest.builder().build();

                Identity.getSignInClient(this).getPhoneNumberHintIntent(request)
                        .addOnSuccessListener(result -> {
                            try {
                                phoneNumberHintLauncher.launch(new IntentSenderRequest.Builder(result.getIntentSender()).build());
                            } catch (Exception e) {
                                if (Constant_wooden.Debug) e.printStackTrace();
                            }
                        })
                        .addOnFailureListener(Throwable::printStackTrace);

            }

        });

        if (StaticVariate_wooden.Select_Country_wooden.equalsIgnoreCase(Constant_wooden.Country_Kenya_wooden))
            mobileTitleTv_wooden.setText(getString(R.string.activity_login_enter_phone_num_ksh));
        else mobileTitleTv_wooden.setText(getString(R.string.activity_login_enter_phone_num));

        //登录前初始化
        AnalyticsUtil_wooden.INSTANCE.initDevice(BaseApplication_wooden.getApplication());

        //获取AppShowInfo
        //HttpManager.getInstance().getAppShowInfo();
    }

    @Override
    public void onRequestOtpCodeResponse_wooden(JSONObject jsonObject) {

        String directLoginFlag = StringUtil_wooden.getSafeString_wooden(jsonObject.optString("directLoginFlag"));

        if (directLoginFlag.equalsIgnoreCase("YES")) {//不需要验证码直接登录
            HttpManager_wooden.getInstance_wooden().userLoginOldUser_wooden(StringUtil_wooden.getSafeString_wooden(phoneNumEt_wooden.gText()));
        } else {
            UserInfoHelper_wooden.getInstance_wooden().setMobile_wooden(phoneNumEt_wooden.gText());
            startActivity_wooden(LoginVerCodeActivity_wooden.class);
        }
    }

    public void onAppShowInfoResponse_wooden() {

        countrySv_wooden.setInput_wooden(StaticVariate_wooden.Select_Country_wooden);

        int currentVersion = BaseApplication_wooden.getApplication().versionCode();

        if (currentVersion < AppShowInfo_wooden.getInstance().minVersion()){
            //强制更新
            new UpgradeDialog_wooden(this,true,null).show();
            return;
        }else if (currentVersion < AppShowInfo_wooden.getInstance().lastVersion()){
            //提示更新
            new UpgradeDialog_wooden(this,false, () -> {

                try {
                    AnalyticsUtil_wooden.INSTANCE.init(BaseApplication_wooden.getApplication());
                } catch (Exception e) {
                    if (Constant_wooden.Debug) e.printStackTrace();
                }

                if (UserInfoHelper_wooden.getInstance_wooden().didLogin_wooden()) {
                    HttpManager_wooden.getInstance_wooden().requestUserProcess_wooden();
                }

            }).show();
            return;
        }

        try {
            AnalyticsUtil_wooden.INSTANCE.init(BaseApplication_wooden.getApplication());
        } catch (Exception e) {
            if (Constant_wooden.Debug) e.printStackTrace();
        }

        if (UserInfoHelper_wooden.getInstance_wooden().didLogin_wooden()) {
            HttpManager_wooden.getInstance_wooden().requestUserProcess_wooden();
        }


    }
}